package com.wang.designpattern.singleton.type3;

public class SingletonTest03 {

    public static void main(String[] args) {
        System.out.println("懒汉式（线程安全，同步方法）");
        Singleton singleton1 = Singleton.getInstance();
        Singleton singleton2 = Singleton.getInstance();
        System.out.println(singleton1 == singleton2);
        System.out.println("singleton1.hashCode() == " + singleton1.hashCode());
        System.out.println("singleton2.hashCode() == " + singleton2.hashCode());
    }

}

class Singleton {
    // 1、私有化构造函数，外部不能new
    private Singleton() {}

    // 2、私有化静态成员变量
    private static Singleton instance;


    // 4、提供一个公有的静态方法，返回对象，加入同步处理代码synchronized，解决线程安全问题
    public static synchronized Singleton getInstance() {
        if (null == instance) {
            instance = new Singleton();
        }
        return instance;
    }
}
